<?php namespace app\hotel\controller;
/**
 * Created by PhpStorm.
 * User: Administrator

 */
use think\Controller;
use app\hotel\model\WeuserModel;
use cmf\controller\BaseController;
class AuthController extends  BaseController{

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 通过 code 获取 AccessToken 和 openid
     * @return bool|array
     */

    public function callBack(){

          $data   =  $this->getOauthAccessToken();
          $this->getuserinfo($data);

    }

    /**
     * 通过 code 获取 AccessToken 和 openid
     * @return bool|array
     */

   public function    getOauthAccessToken(){

       //获取到的code
       $code = isset($_GET['code']) ? $_GET['code'] : '';
       if (empty($code)) {
           exit("getOauthAccessToken Fail, Because there is no access to the code value in get.".config('appID'));
       }
       $access_token = session('access_token');

       if($access_token == "" || time() - $access_token['expires_time'] >0){

               $url =   'https://api.weixin.qq.com/sns/oauth2/access_token?appid='
                   .config('appID').'&secret='.config('appSecret').'&code='.$code.'&grant_type=authorization_code';
               //获取access_token和openid,转换为数组
               $data =$this->postCurl($url);
               $data = json_decode($data,true);
               session('access_token',$data);
               session('access_token.expires_time',time()+ 7200);
               session('openid',$data['openid']);

               return $data;
           }else{
               return  session('access_token');
           }
   }

    /*
     * 获取用户信息
     * */
    public  function  getuserinfo($data){
        //获取用户的基本信息，并将用户的唯一标识保存在session中
		 	$userurl = 'https://api.weixin.qq.com/sns/userinfo?access_token='
                .$data['access_token'].'&openid='.$data['openid'].'&lang=zh_CN';
			 $user_data = $this->postCurl($userurl);
             $user_data = json_decode($user_data,true);

            if($user_data != null && $user_data['openid']){

                //将用户信息存在数据库中,同时将用户在数据库中唯一的标识保存在session中
                $array = [];
                $array['openid'] = $user_data['openid'];
                $array['nickname'] = self::emoji_encode($user_data['nickname']);
                $array['avatar'] = $user_data['headimgurl'];
                $array['create_time'] = time();

                //实例化用户表model
                $wechat_user = new WeuserModel();
                //先判断用户数据是不是已经存储了，如果存储了获取用户在数据库中的唯一标识
                $openid = $wechat_user->where('openid', $array['openid'])->field('openid')->find();

                if($openid){
                    session('user_id',$openid['openid']);
                }else{
                   $inserid = $wechat_user->save($array);
                    $wechat_user->isUpdate(false)->allowField(true)->save($array);
                    //将用户在数据库中的唯一表示保存在session中
                    session('user_id',$array['openid']);
                }
                //跳转网页
                $this->redirect(config('tiao_url'));
            }else{
                exit('获取用户信息失败！');
            }
    }
    /**
     * 处理特殊昵称
     */
    private function emoji_encode($nickname){
        $strEncode = '';
        $length = mb_strlen($nickname,'utf-8');
        for ($i=0; $i < $length; $i++) {
            $_tmpStr = mb_substr($nickname,$i,1,'utf-8');
            if(strlen($_tmpStr) >= 4){
                $strEncode .= '[[EMOJI:'.rawurlencode($_tmpStr).']]';
            }else{
                $strEncode .= $_tmpStr;
            }
        }
        return $strEncode;
    }
    /*
     * CURL
     */
    public function postCurl($url, $option=array(), $header = array(), $type = 'POST',$setopt = 10) {
        $curl = curl_init (); // 启动一个CURL会话
        if($curl !== false){
            curl_setopt ( $curl, CURLOPT_URL, $url ); // 要访问的地址
            curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE ); // 对认证证书来源的检查
            curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE ); // 从证书中检查SSL加密算法是否存在
            curl_setopt ( $curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)' ); // 模拟用户使用的浏览器
            if (! empty ( $option )) {
                curl_setopt ( $curl, CURLOPT_POSTFIELDS, $option ); // Post提交的数据包
            }
            curl_setopt ( $curl, CURLOPT_TIMEOUT, $setopt ); // 设置超时限制防止死循环
            if(empty($header)){
                $header = array();
            }
            curl_setopt ( $curl, CURLOPT_HTTPHEADER, $header ); // 设置HTTP头
            curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // 获取的信息以文件流的形式返回
            curl_setopt ( $curl, CURLOPT_CUSTOMREQUEST, $type );
            curl_getinfo($curl, CURLINFO_HTTP_CODE); // 获取Status Code 正确返回200
            $result = curl_exec ( $curl ); // 执行操作
            curl_close ( $curl ); // 关闭CURL会话
            return $result;
        }else{
            return false;
        }
    }
}
